<template>
  <div class="userForm">
    <el-form :model="ruleForm" :rules="rules" ref="ruleForm"  class="loginForm">
      <h2 class="title">欢迎使用</h2>
      <el-form-item prop="username">
        <el-input placeholder="请输入账号" v-model="ruleForm.username" prefix-icon="el-icon-s-custom"></el-input>
      </el-form-item>
      <el-form-item prop="password">
        <el-input placeholder="请输入密码" type="password" v-model="ruleForm.password" autocomplete="off" prefix-icon="el-icon-lock"></el-input>
      </el-form-item>
      <el-form-item class="btn">
        <el-button type="primary" style="width: 100%" @click="submitForm('ruleForm')">登录</el-button>
<!--        <el-button @click="resetForm('ruleForm')">重置</el-button>-->
        <el-link type="primary" href="/register">去注册</el-link>
      </el-form-item>

    </el-form>


  </div>
</template>

<script>
export default {
  data() {
    return {
      ruleForm: {
        username: '',
        password:''
      },
      rules: {
        username: [
          { required: true, message: '请输入账号', trigger: 'blur' },
          { min: 1, max: 18, message: '长度为18个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 5, message: '长度大于5', trigger: 'blur'}
        ]
      }
    };
  },
  methods: {
    submitForm(formName) {
      // const valid = this.$refs.loginForm.validate();
      // if (valid){
      //   this.axios.post('http://127.0.0.1:7777/login', formName)
      // }

      this.$refs[formName].validate(async valid => {
        console.log("表单验证信息："+valid)
        if (valid) {
          const {data:res} = await this.$http.post("/login",this.ruleForm);
          console.log("后端返回的数据：",res)
          if (res.flag === "OK"){
            this.$message.success("登录成功");

            localStorage.setItem("user",res.user);
            window.sessionStorage.setItem("user",res.user);
            await this.$router.push({path: "/home"});
          }else{
            this.$message.error("账号或密码错误");
          }
          //alert('submit!');
          // console.log(res);
        } else {
          this.$message.error("请输入有效信息");
          console.log('error submit!!');
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    }
  }
}
</script>

<style>
  .userForm{
    background: aliceblue;
    width: 350px;
    border-radius: 15px;
    background-clip: padding-box;
    margin: 180px auto;
    padding: 15px 35px 15px 35px;
    border: 1px solid #cecece;
    box-shadow: 0 0 25px #cac6c6;
  }
  .title{
    text-align: center;
    margin: 0px auto 40px auto;
  }


</style>